from flask import Blueprint, request, jsonify, redirect
import json, random, time, requests
from util.comm import get_ali_object
from util.myredis import r
from models.user import *
from elasticsearch import Elasticsearch

up_blue = Blueprint("upblue",__name__)



@up_blue.route('/get_user')
def get_user():
    user_id = request.args.get('user_id')
    if not user_id:
        return jsonify({
            'code':400,
            'msg':"请重新登录"
        })
    use = Users.query.filter_by(id=user_id).first()
    print(use)
    lst = []
    lst.append({
        'id':use.id,
        'mobile':use.mobile,
        'money':use.money,
        'lock_money':use.lock_moeny
    })
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':lst
    })

@up_blue.route("/topup_user")
def topup_user():
    user_id = request.args.get('user_id')
    money = request.args.get('money')
    # 订单号
    number = str(int(time.time())) + str(user_id) + str(random.randint(100000,999999))
    # 订单生成时间
    create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(create_time)
    try:
        user_order = Uptop_Orders(user_id=int(user_id),number=number,money=float(money))
        db.session.add(user_order)
        db.session.commit()
        times = int(time.time()) + 1830
        r.sortedset_add('top_up_order',number,times)
        pay = get_ali_object()
        query_params = pay.direct_pay(
            subject="账号充值",  # 商品简单描述
            out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=float(money),  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址
        return jsonify({
            'code':200,
            'msg':"ok",
            'url':pay_url
        })
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify({
            'code':400,
            'msg':"加入订单生成失败"
        })

@up_blue.route('/callback/')
def Callback():
    # 获取支付返回的参数
    data = request.args
    # 对参数进行处理
    data = {k: v for k, v in data.items()}
    # 从字典中将sign删除
    sign = data.pop('sign')
    # 获取支付宝对象
    alipay = get_ali_object()
    # 调用验签
    flag = alipay.verify(data, sign)
    # 订单号
    order_id = data.pop('out_trade_no')
    # 支付宝流水号
    zfb_auth = data.pop('auth_app_id')
    # 获取当前时间
    times = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    orders = Uptop_Orders.query.filter_by(number=order_id).first()
    user = Users.query.filter_by(id=int(orders.user_id)).first()
    if flag == True:
        r.sortedset_delete("top_up_order", order_id)
        try:
            monet_orders = Money_Orders.query.filter_by(number=order_id).first()
            if monet_orders:
                return jsonify({
                    'code':400,
                    'msg':"后端错误"
                })
            else:
                Uptop_Orders.query.filter_by(number=order_id).update(
                    {'status': 1, 'serial_num': zfb_auth, "pay_time": times})
                Users.query.filter_by(id=int(orders.user_id)).update({"money": float(user.money) + float(orders.money)})
                money_orders = Money_Orders(user_id=int(user.id),money=float(orders.money),number=order_id, type=1)
                db.session.add(money_orders)
                db.session.commit()
                return redirect('http://localhost:8080/admin_user')
        except Exception as e:
            print(e)
            db.session.commit()
            return jsonify({
                'code':400,
                'msg':"回调失败"
            })

es = Elasticsearch('http://43.143.147.107:9200/')










